<?php
/**
 * author: NanQi
 * datetime: 2019/9/14 21:55
 */
namespace NanQi\Hope\Traits;

trait ModelEncryptionTrait
{
    use EncryptionTrait;

    /**
     * 是否加密
     * @param string $key
     * @return bool
     */
    public function isEncryptable(string $key) : bool
    {
        if (!isset($this->encryptable)) {
            return false;
        }
        return in_array($key, $this->encryptable);
    }


    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);
        if ($this->isEncryptable($key)) {
            $value = $this->decryptAttribute($value);
        }
        return $value;
    }

    public function setAttribute($key, $value)
    {
        if ($this->isEncryptable($key)) {
            $value = $this->encryptAttribute($value);
        }
        return parent::setAttribute($key, $value);
    }

    public function getArrayableAttributes()
    {
        $attributes = parent::getArrayableAttributes();
        foreach ($attributes as $key => $attribute) {
            if ($this->isEncryptable($key)) {
                $attributes[$key] = $this->decryptAttribute($attribute);
            }
        }
        return $attributes;
    }
}
